<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8" style="margin-top: 20px">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">{{
          $t("export_payroll_calculation") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-copy-document" size="mini" @click="handleSyncData">{{
          $t("synchronize_attendance_records") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-refresh" size="mini" @click="handleOperation">{{
          salaryCalculationForm.isCalculation == 0
          ? $t("calculate")
          : $t("recalculate")
        }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-bottom" size="mini" @click="handleExport">{{ $t("download_template")
        }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-top" size="mini" @click="handleImport">{{ $t("import_payroll_data")
        }}</el-button>
      </el-col>
    </el-row>

    <el-table style="margin-top: 10px" v-loading="loading" :data="tableList" border :max-height="tableHeight">
      <el-table-column :label="item.title" align="center" v-for="(item, index) in tableColumn" :key="index"
        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div v-for="(listItem, listIndex) in tableList[scope.$index].dataList" :key="listIndex">
            <span v-if="index == listIndex">
              <template v-if="Object.prototype.toString.call(listItem) === '[object Object]' && listItem.ifChange">
                <span v-if="listItem.ifChange == 1" style="color: #ffba00;"> {{ listItem.projectDataSourceValue }}</span>
                <span v-else>{{ listItem.projectDataSourceValue }}</span>
              </template>
              <template v-else-if="Object.prototype.toString.call(listItem) === '[object Object]' && !listItem.ifChange">
                <span v-if="listItem.changed" style="color: #ffba00;"> {{ listItem.totalMoney || '-' }}</span>
                <span v-else>{{ listItem.totalMoney || '-' }}</span>
                <el-tooltip class="item" effect="dark" :content="listItem.projectDataSourceValue" placement="right">
                  <i class="el-icon-warning-outline" style="font-size: 18px; margin-left: 8px; cursor: pointer"></i>
                </el-tooltip>
              </template>
              <template v-else>
                {{ listItem }}
              </template>
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('action')" align="center" class-name="small-padding fixed-width" width="160"
        fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">{{ $t("modify")
          }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">{{ $t("delete")
          }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" 
      :page-sizes="[10,20,30,50,100, 200]"
      />

    <div style="text-align: center; margin-top: 60px">
      <el-button type="primary" plain @click="preStep">{{
        $t("re_import_data")
      }}</el-button>
      <el-button type="primary" @click="nextStep">{{
        $t("save_as_draft")
      }}</el-button>
    </div>

    <!-- 添加或修改薪酬运算列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-form-item :label="item.title" v-for="(item, index) in tableColumn" :key="index">
          <template
            v-if="Object.prototype.toString.call(form.dataList[index]) === '[object Object]' && !form.dataList[index].ifChange">
            <el-input v-model="form.dataList[index].totalMoney" :placeholder="$t('please_enter', { name: '' })"
              maxlength="10"
              oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}" />
          </template>
          <template
            v-else-if="Object.prototype.toString.call(form.dataList[index]) === '[object Object]' && form.dataList[index].ifChange">
            <el-input v-model="form.dataList[index].projectDataSourceValue"
              :placeholder="$t('please_enter', { name: '' })" maxlength="10"
              oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}" />
          </template>
          <el-input v-model="form.dataList[index]" placeholder="" :disabled="item.title != $t('attendance_days')"
            v-else />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{
          $t("confirm")
        }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>
    <!-- 导入弹窗 -->
    <importModal ref="importModal" :title="$t('import')" downloadUrl=""
      uploadUrl="/salary/salaryCalculation/3uploadTemplate.do" :downloadName="$t('download_template')"
      @refreshList="getList"></importModal>
  </div>
</template>

<script>
import importModal from "@/views/components/custom/importModal.vue";
import {
  getSalaryCalculationEmpList,
  synchronizeAttendanceData,
  removeEmp,
  calculation,
  updateCalculation,
} from "@/api/salary/salaryCalculation";

export default {
  components: { importModal },
  props: {
    salaryCalculationForm: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  dicts: [],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      tableColumn: [],
      tableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      form: {
        dataList: [],
      },
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      getSalaryCalculationEmpList({
        ...this.queryParams,
        salaryCalculationId: this.salaryCalculationForm.id,
        type: 1
      }).then((res) => {
        this.tableColumn = res.data.headerList.map((item) => {
          return {
            title: item,
          };
        });
        let list = JSON.parse(JSON.stringify(res.data.empInfoList))
        list.forEach((item) => {
           // 判断数据中第几项后是需要动态改变颜色的数据
          var flag = item.dataList.findIndex(item => {
            return item === '============';
          })
           // 剔除不需要展示的项
          item.dataList.splice(flag,1)
          //如果数据中不是对象并且返回了数值后面带是否上色的标识 加上色字段
          item.dataList.forEach((ele, index) => {
            if (index > (flag-1)) {
              if (typeof ele != 'object') {
                if ((ele.indexOf('(true)') != -1)) {
                  item.dataList[index] = {
                    projectDataSourceValue: ele.split('(')[0],
                    ifChange: 1
                  }
                }
                else {
                  item.dataList[index] = {
                    projectDataSourceValue: ele.split('(')[0],
                    ifChange: 2
                  }
                }
              }
            }
          })
        });
        this.tableList = list;
        this.loading = false;
      });
    },
    /** 运算/重新运算 */
    handleOperation() {
      this.$modal
        .confirm(this.$t("calculation_salary"))
        .then(() => {
          calculation(this.salaryCalculationForm.id).then((res) => {
            this.$modal.msgSuccess(this.$t("operation_successful"));
            this.getList();
            this.$emit("operationFinish", this.salaryCalculationForm);
          });
        })
        .catch(() => { });
    },
    /** 同步数据 */
    handleSyncData() {
      this.$modal
        .confirm(this.$t("synchronize_attendance_data"))
        .then(() => {
          synchronizeAttendanceData(this.salaryCalculationForm.id).then(
            (res) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.getList();
            }
          );
        })
        .catch(() => { });
    },
    /** 修改 */
    handleUpdate(row) {
      this.title = this.$t("modify");
      this.open = true;
      this.form = { ...row };
    },
    /** 删除 */
    handleDelete(row) {
      this.$modal
        .confirm(this.$t("delete_data"))
        .then(function () {
          return removeEmp(row.salaryCalculationEmpId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("operation_successful"));
        })
        .catch(() => { });
    },
    cancel() {
      this.open = false;
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {

          this.$confirm(this.$t("edit_dialog"), this.$t("prompt"), {
            type: "warning",
          }).then((res) => {
            let list = this.form.dataList.filter((item) => {
              return Object.prototype.toString.call(item) === "[object Object]";
            });
            let attendanceDaysIndex = this.tableColumn.findIndex((item) => {
              return item.title == this.$t("attendance_days");
            });
            updateCalculation({
              salaryCalculationId: this.salaryCalculationForm.id,
              salaryCalculationEmpId: this.form.salaryCalculationEmpId,
              empProjectResultList: list,
              attendanceDays: this.form.dataList[attendanceDaysIndex].projectDataSourceValue,
            }).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          });
        }
      });
    },
    /** 导出 */
    handleExport() {
      this.download(
        "salary/salaryCalculation/3downloadTemplate.do",
        { salaryCalculationId: this.salaryCalculationForm.id },
        `salaryCalculation_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入 */
    handleImport() {
      this.$refs.importModal.showModal();
    },
    //上一步
    preStep() {
      this.$emit("changeStatus", 1);
    },
    //下一步
    nextStep() {
      this.$emit("changeStatus", 4);
    },
  },
};
</script>
<style scoped lang="scss"></style>
